package com.group3.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.group3.Feign.OrderServiceFeign;
import com.group3.Feign.UserServiceFeign;
import com.group3.common.result.ApiResponse;
import com.group3.model.Order;
import com.group3.model.Payment;
import com.group3.model.User;
import com.group3.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private OrderServiceFeign orderServiceFeign;

     @Autowired
      private UserServiceFeign userServiceFeign;

     @Autowired
     private RocketMQTemplate rocketMQTemplate;

    @RequestMapping("/getPaymentList")
    public List<Payment> getPaymentList()
    {
        return paymentService.list();
    }
    @RequestMapping("/getPaymentById/{id}")
    public Object getPaymentById(@PathVariable Integer id)
    {
        return paymentService.getById(id);
    }


    @RequestMapping ("/getPaymentUser/{pid}")
    public ApiResponse getPaymentUser(@PathVariable Integer pid) {
        log.info("获取用户{}的支付信息",pid);
       Payment payment =paymentService.getById(pid);
        User user=userServiceFeign.getUserByUid(payment.getUid());
        return ApiResponse.success("获取成功", user);
    }

    @RequestMapping("/getPaymentByOid/{oid}")
    public Object getPaymentByOid(@PathVariable Integer oid) {
        QueryWrapper<Payment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("oid", oid);
        return paymentService.getOne(queryWrapper);
    }

    @RequestMapping ("/paymentOrder/{oid}")
    public Payment addPayment(@PathVariable Integer oid) {
        log  .info("支付订单{}",oid);
        // 1. 获取订单信息
        Order order = orderServiceFeign.getOrderByOid(oid);
        rocketMQTemplate.syncSendOrderly("payment-order", "获取订单" + oid + ": " + "信息", "orderly-payment-order-queue");
        Payment payment = new Payment();
        // 2. 校验订单状态（假设0是未支付状态）
        if (order != null && order.getStatus() == 0) {
            // 3. 更新订单状态为已支付（1是已支付状态）
            order.setStatus(1);
            rocketMQTemplate.syncSendOrderly("payment-order", "订单" + oid + ": " + "支付成功", "orderly-payment-order-queue");
            boolean updateResult = orderServiceFeign.updateOrder(order);
            // 4. 创建支付记录
            if (updateResult) {
                payment.setOid(oid);
                payment.setUid(order.getUid());
                payment.setUsername(order.getUsername());
                payment.setPid(order.getPid());
                payment.setPname(order.getPname());
                payment.setPprice(order.getPprice());
                payment.setNumber(order.getNumber());
                payment.setTotal(order.getPprice() * order.getNumber()); // 计算总金额
                payment.setStatus(1); // 设置支付状态为已支付
                paymentService.save(payment);
                rocketMQTemplate.syncSendOrderly("payment-order", "创建订单" + oid + ": " + "支付记录", "orderly-payment-order-queue");
            }
        }
        return payment;
    }

    // 处理订单取消时的退款
    @RequestMapping("/refundOrder/{oid}")
    public boolean refundOrder(@PathVariable Integer oid) {
        QueryWrapper<Payment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("oid", oid);
        Payment payment = paymentService.getOne(queryWrapper);
        if (payment == null) {
            return false;
        }
        if (payment.getStatus() != 1) {
            return false;
        }
        rocketMQTemplate.asyncSend("refund-order", "处理订单" + oid + "取消时的退款", new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("退款成功，结果为{}", sendResult);
            }
            @Override
            public void onException(Throwable throwable) {
                log.error("退款失败，异常为", throwable);
            }
        });
        // 模拟退款操作（实际需调用第三方支付接口）
        payment.setStatus(2); // 2表示已退款
        return paymentService.updateById(payment);
    }

    // 处理退款申请
    @RequestMapping("/initiateRefund/{oid}")
    public boolean initiateRefund(@PathVariable Integer oid) {
        QueryWrapper<Payment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("oid", oid);
        Payment payment = paymentService.getOne(queryWrapper);
        if (payment == null) {
            return false;
        }
        if (payment.getStatus() != 1) {
            return false;
        }
        rocketMQTemplate.asyncSend("initiate-refund", "处理订单" + oid + "退款申请", new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("退款申请成功，结果为{}", sendResult);
            }
            @Override
            public void onException(Throwable throwable) {
                log.error("退款申请失败，异常为", throwable);
            }
        });
        payment.setStatus(3); // 3表示退款中
        return paymentService.updateById(payment);
    }

}
